package com.yanqu.controller;

import com.yanqu.CollectServer;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

@RestController
@RequestMapping("/")
public class CollectDataController {

    private static final Logger logger = LogManager.getLogger(CollectDataController.class.getName());

    @RequestMapping("/heart")
    @ResponseBody
    public String heart(){
        return String.valueOf(System.currentTimeMillis());
    }

    @PostMapping("/sys_service")
    public Object startUpdate(HttpServletRequest request) {
        long serverId = 0;
        if(request.getParameterMap().containsKey("serverId")){
            serverId = Long.valueOf(request.getParameter("serverId"));
        }
        boolean gzip = false;
        if(request.getParameterMap().containsKey("gzip") || !StringUtils.isNullOrEmpty(request.getHeader("gzip"))){
            gzip = true;
        }
        long start = System.currentTimeMillis();
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if(gzip){
                byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(request.getInputStream());
                ByteArrayInputStream in = new ByteArrayInputStream(compressed);
                inputStream = new GZIPInputStream(in);
            }
            StringBuilder out = new StringBuilder();
            byte[] b = new byte[4096];
            long total = 0L;
            for (int n; (n = inputStream.read(b)) != -1; ) {
                out.append(new String(b, 0, n));
                total += n;
            }
            CollectServer.getFileWrite().add(out);
            long cost = System.currentTimeMillis() - start;
            if(cost > 10) {
                logger.info("tda collect log from {}  cost {}", serverId, cost);
            }
            CollectStatistic.addReceive(serverId, total);
        }catch (Exception e){
            logger.error(e);
            return "{\"ret\": 100}";
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        return "{\"ret\": 0}";
    }

    @PostMapping("/")
    public Object startUpdate2(HttpServletRequest request) {
        return startUpdate(request);
    }

}
